package com.micai.springboot.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.micai.springboot.base.BaseController;
import com.micai.springboot.base.servlet.ServletUtil;
import com.micai.springboot.dto.sys.SLogDto;
import com.micai.springboot.entity.sys.SLogEntity;
import com.micai.springboot.service.SLogService;
import com.micai.springboot.util.MessageUtils;
import com.micai.springboot.view.PoiExcelExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 描述：日志管理
 * <p>
 * Author: 赵新国
 * Date: 2017/11/14 15:21
 */
@Controller
@RequestMapping("/admin/log")
public class AdminLogController extends BaseController {

    @Autowired
    private SLogService logService;

    private static int corePoolSize = Runtime.getRuntime().availableProcessors();
    //多线程导出日志  调整队列数 拒绝服务
    private static ThreadPoolExecutor executor  = new ThreadPoolExecutor(corePoolSize, corePoolSize+1, 10l, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(10));

    /**
     * 分页查询日志列表
     * @param model
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@RequestParam(value="pageNum", defaultValue="1") int pageNum,
                       @RequestParam(value="pageSize", defaultValue="10") int pageSize,
                       @RequestParam(required = false) String requestType,
                       @RequestParam(required = false) String startDate,
                       @RequestParam(required = false) String endDate, Model model) {
        Page<SLogEntity> logEntities = logService.getLogByPage(pageNum, pageSize, requestType, startDate, endDate);
        PageInfo<SLogEntity> page = new PageInfo<SLogEntity>(logEntities);
        model.addAttribute("page",page);
        // 参数回显
        model.addAttribute("requestType", requestType);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        return "admin/log/logList";
    }

    /**
     * 导出日志信息
     *
     * @return
     */
    @GetMapping(value = "/export")
    public void export(@RequestParam(required = false) String requestType,
                       @RequestParam(required = false) String startDate,
                       @RequestParam(required = false) String endDate,
                       HttpServletRequest request, HttpServletResponse response) {
        String fileName = "日志数据.xls";
        ServletUtil su = new ServletUtil(fileName, request, response);
        su.poiExcelServlet();
        String[] heads = {"ID","请求地址","请求类型","创建时间","更新时间"};
        String[] cols = {"id","requestUri","requestType","tsInsert","tsUpdate"};
        int[] numerics = {2};
        List<SLogDto> logDtos = logService.getLogs(requestType, startDate, endDate);
        if (logDtos == null || logDtos.isEmpty()) {
            return;
        }
        ServletUtil suresp = new ServletUtil(response);
        long start = System.currentTimeMillis();
        new PoiExcelExport<SLogDto>(fileName, heads, cols, logDtos, numerics, suresp.getOut()).exportExcel();
        long end = System.currentTimeMillis();
        logger.info("导出Excel耗时：" + (end -start) + " 毫秒.");
    }

    /**
     * 多线程导出日志信息
     *
     * @return
     */
    @GetMapping(value = "/mexport")
    public void mexport(@RequestParam(required = false) String requestType,
                        @RequestParam(required = false) String startDate,
                        @RequestParam(required = false) String endDate,
                        HttpServletRequest request, HttpServletResponse response) {
        String fileName = "多线程导出日志数据.xls";
        ServletUtil su = new ServletUtil(fileName, request, response);
        su.poiExcelServlet();
        String[] heads = {"ID","请求地址","请求类型","创建时间","更新时间"};
        String[] cols = {"id","requestUri","requestType","tsInsert","tsUpdate"};
        int[] numerics = {2};
        List<SLogDto> logDtos = logService.getLogs(requestType, startDate, endDate);
        if (logDtos == null || logDtos.isEmpty()) {
            return;
        }
        ServletUtil servletUtil = new ServletUtil(response);
        long start = System.currentTimeMillis();
        /*new PoiExcelExport<SLogDto>(fileName, heads, cols, logDtos, numerics, servletUtil.getOut()).exportExcel();*/
        executor.submit(new exportLog(fileName, heads, cols, logDtos, numerics, servletUtil));
        long end = System.currentTimeMillis();
        logger.info("多线程导出Excel耗时：" + (end -start) + " 毫秒.");
    }

    class exportLog implements Callable<String> {
        private String fileName;
        private String[] heads;
        private String[] cols;
        private List<SLogDto> logDtos;
        private int [] numerics;
        private ServletUtil servletUtil;

        public exportLog(String fileName, String[] heads, String[] cols, List<SLogDto> logDtos, int[] numerics, ServletUtil servletUtil) {
            this.fileName = fileName;
            this.heads = heads;
            this.cols = cols;
            this.logDtos = logDtos;
            this.numerics = numerics;
            this.servletUtil = servletUtil;
        }

        @Override
        public String call() {
            // 执行导出日志数据
            PoiExcelExport<SLogDto> poiExcelExport = new PoiExcelExport<>(fileName, heads, cols, logDtos, numerics, servletUtil.getOut());
            poiExcelExport.exportExcel();
            return "success";
        }
    }

    /**
     * 根据ID删除日志信息
     *
     * @param ids
     * @return
     */
    @PostMapping(value = "/delete")
    @ResponseBody
    public Map<String, Object> delete(@RequestParam("ids[]") List<Long> ids) {
        Map<String, Object> retMap = MessageUtils.success();
        try {
            // 删除日志
            logService.deleteBatchIds(ids);
            retMap = MessageUtils.success("删除成功");
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }

}
